<div class="excelDataUploadModel" id="add-upload-file">
    <div class="layui-form-item">
        <label class="layui-form-label">
            <p class="subtext">温馨提示：</p>
        </label>
        <div class="layui-input-block">
            <p class="subtext">只能上传xls/xlsx文件</p>
        </div>
    </div>
    <form class="layui-form layui-row">
        <div class="layui-inline layui-row">
            <label class="layui-form-label">文件上传</label>
            <div class="layui-input-block">
                <button id="file-btn-upload" lay-filter="file-btn-upload" class="layui-btn layui-btn-sm layui-btn-normal icon-btn" lay-submit>
                    <i class="layui-icon">&#xe681;</i>上传文件
                </button>
                <button id="file-btn-download" lay-filter="file-btn-download" class="layui-btn layui-btn-sm layui-btn-normal icon-btn" lay-submit>
                    <i class="layui-icon">&#xe601;</i>模板下载
                </button>
            </div>
        </div>
        <div class="layui-inline layui-row">
            <label class="layui-form-label">文件名称</label>
            <div class="layui-input-block">
               <p id="file_name">还没有上传文件哦！</p>
            </div>
        </div>
        <div class="layui-inline layui-row">
            <label class="layui-form-label">数据选择</label>
            <div class="layui-input-block">
                <select name="sheetName" lay-verify="" id="data-choose">

                </select>
            </div>
        </div>
        <div class="layui-inline layui-row year_month">
            <label class="layui-form-label">报告期</label>
            <div class="layui-input-block">
                <input type="text" name="report" class="layui-input" id="reportYear" placeholder="yyyy">
            </div>
        </div>
        <div class="report_quarter" style="display: none">
            <div class="layui-inline layui-row">
                <label class="layui-form-label">年</label>
                <div class="layui-input-block">
                    <select name="report_quarter_year" id="report_quarter_year" lay-verify="" lay-filter="report_quarter_year">

                    </select>
                </div>
            </div>
            <div class="layui-inline layui-row">
                <label class="layui-form-label">季度</label>
                <div class="layui-input-block">
                    <select name="report_quarter_mouth" id="report_quarter_mounth" lay-verify="" lay-filter="report_quarter_mounth">
                        <option value="">请选择季度</option>
                        <option value="1">第一季度</option>
                        <option value="2">第二季度</option>
                        <option value="3">第三季度</option>
                        <option value="4">第四季度</option>
                    </select>
                </div>
            </div>
        </div>
        <div id="datavIsMulti">

        </div>
        <div id="chooseVersion" style="display: none">
            <label class="layui-form-label">选择版本</label>
            <div class="layui-input-block">
                <select name="vaersionName" id="version-name" lay-verify="">

                </select>
            </div>
        </div>
        <div class="layui-inline layui-row">
            <label class="layui-form-label">追加方式</label>
            <div class="layui-input-block">
                <select name="importMethod" lay-verify="">
                    <option value="0">覆盖当前对象表</option>
                    <option value="1">追加当前对象表</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn layui-btn-sm" lay-filter="analysis-upload" lay-submit >解析上传</button>
        </div>
    </form>

</div>
<!--渲染对象分类-->
<script type="text/tmpl" id="template-datachoose-tmpl">
    <option value="">请选择要导入的数据</option>
     {{each data_choose}}
        <option value="{{$value.name}}">{{$value.name}}</option>
    {{/each}}
</script>
<!--渲染对象分类-->
<script type="text/tmpl" id="template-datavIsMulti-tmpl">
        <div class="layui-inline layui-row">
            <label class="layui-form-label">创建新版本</label>
            <div class="layui-input-block">
                <select id="isDatavIsMulti"  lay-filter="isDatavIsMulti">
                    <option value="0">是</option>
                    <option value="1">否</option>
                </select>
            </div>
        </div>

</script>
<!--渲染对象分类-->
<script type="text/tmpl" id="template-pversion-tmpl">
    <option value="">请选择版本</option>
     {{each data}}
        <option value="{{$value.id}}">{{$value.pversion}}</option>
    {{/each}}
</script>
<!--渲染季度的年份-->
<script type="text/tmpl" id="template-quarter-tmpl">
    <option value="">请选择年份</option>
     {{each dateArr}}
        <option value="{{$value}}">{{$value}}</option>
    {{/each}}
</script>
<script>
    layui.use(['layer', 'form', 'admin','laydate','upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var Authorization;
        var file_name;
        var urlData = window.mSelUser;  // 列表页面传递的数据，也可以使用top.xxx
        var userInfo = getAuthority();
        var micro_month;
        var micro_year;
        //获取当前年份
        function getReportYear() {
            var date = new Date();
            let new_year = date.getFullYear()-19; //获取完整的年份(4位)
            let dateArr = [];
            for(let i =0;i<19;i++){
                dateArr.push(new_year+=1)
            }
            var str = template("template-quarter-tmpl",{dateArr});
            document.getElementById("report_quarter_year").innerHTML = str;
            form.render('select')
        }
        //获取权限方法
        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;
            getReportYear();
            if(urlData.miid.datavIsMulti){
                var str = template("template-datavIsMulti-tmpl",{});
                document.getElementById("datavIsMulti").innerHTML = str;
                form.render('select')
            }
        }
        if(urlData.miid.reportType == "1"){
            //年选择器
            laydate.render({
                elem: '#reportYear'
                ,type: 'year',done: function(value, date, endDate){
                    micro_month = value.split('-')[1]?value.split('-')[1].replace(/\b(0+)/gi,""):0
                    micro_year = value.split('-')[0]
                }
            });
            }else if(urlData.miid.reportType == "2"){
            laydate.render({
                elem: '#reportYear'
                ,type: 'month',
                done: function(value, date, endDate){
                    micro_month = value.split('-')[1]?value.split('-')[1].replace(/\b(0+)/gi,""):0
                    micro_year = value.split('-')[0]
                }
            });
        }else {
            $(".report_quarter").css("display","block");
            $(".year_month").css("display","none")
            form.on('select(report_quarter_year)', function(isMulti){
                micro_year = isMulti.value
            });
            form.on('select(report_quarter_mounth)', function(isMulti){
                micro_month = isMulti.value
            });
        }

        form.render('select')
        form.on('submit(file-btn-download)', function (data) {
            let url=microUrl.microObject.idenMicroMeta.downloadMicro+'?mitid='+urlData.miid.id;
            let xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头，必须在open后添加
            xhr.setRequestHeader('authorization', Authorization);
            xhr.responseType = 'blob'; // 返回类型blob  blob 存储着大量的二进制数据
            xhr.onload = function (res) {
                if (this.status === 200) {
                    let excelName = decodeURI(xhr.getResponseHeader("filename"));
                    let blob = this.response;
                    let reader = new FileReader();
                    reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签href
                    reader.onload = function (e) {
                        let a = document.createElement('a'); // 转换完成，创建一个a标签用于下载
                        a.download = excelName;
                        a.href = e.target.result;
                        a.click();
                    };
                }
            }
            xhr.send(); // 发送ajax请求
            return false;
        });
        form.on('select(isDatavIsMulti)', function(isMulti){
            if(!micro_year){
                layer.msg('请先选择报告期', {icon: 2});
                return false
            }

            if(isMulti.value=='1'){
                getPverSion();
            }else {
                $('#chooseVersion').css('display','none');
            }
        });
        var uploadUrl = microUrl.microObject.idenMicroMeta.uploadMicro;
        upload.render({
            elem: '#file-btn-upload' //绑定元素
            ,url: uploadUrl //上传接口
            ,accept: 'file',
            headers:{'authorization':Authorization}
            ,done: function(res, file, upload){
                //上传完毕回调
                $('#file_name').html(file_name)
                var data_choose = res.data.sheet;
                file_name = res.data.file
                var str = template("template-datachoose-tmpl",{data_choose});
                document.getElementById("data-choose").innerHTML = str;
                form.render('select')
            }
            ,error: function(err){
                //请求异常回调
                console.log(err)
            }
        });
        form.on('submit(file-btn-upload)', function (data) {

            //执行实例

            return false;
        });
        form.on('submit(analysis-upload)',function (data) {
            let form_year;
            let form_month
            if(urlData.miid.reportType=="1"||urlData.miid.reportType=="2"){
                form_month = data.field.report.split('-')[1]?data.field.report.split('-')[1].replace(/\b(0+)/gi,""):0;
                form_year = data.field.report.split('-')[0]
            }else {
                form_month = data.field.report_quarter_mouth;
                form_year = data.field.report_quarter_year;
            }
            var formData = {
                "fileName": file_name,
                "importMethod": data.field.importMethod,
                "mitid": urlData.miid.id,
                "month": form_month,
                "pversion":  data.field.vaersionName,
                "sheetName": data.field.sheetName,
                "year":form_year,
            };
            axios({
                method: 'post',
                data:formData,
                url:microUrl.microObject.idenMicroMeta.analysisMicro,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 1});
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                    admin.closeDialog('#add-upload-file');
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
            return false;
        })
        function getPverSion() {
            $('#chooseVersion').css('display','block');
            var req = {
                month:micro_month,
                year:micro_year,
                mitmid:urlData.miid.id
            }
            axios.get(microUrl.microObject.idenDbLink.dataPversion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success") {
                        var data = response.data.data;
                        var str = template("template-pversion-tmpl",{data});
                        document.getElementById("version-name").innerHTML = str;
                        form.render('select')
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

    });
</script>